import { firstValueFrom } from 'rxjs';
import { HttpService } from '@nestjs/axios';
import { Injectable } from '@nestjs/common';
import * as svgCaptcha from 'svg-captcha';
import * as path from 'path';
import config from 'src/config/config';
import * as mkdirp from 'mkdirp';
import { createWriteStream, writeFile } from 'fs';
import sizeOf from 'image-size';
import * as nodemailer from 'nodemailer';
import { getMailCodeTemplate } from 'src/config/template';
const Jimp = require('jimp');
import * as lodash from 'lodash';
import * as md5 from 'md5';
@Injectable()
export class ToolsService {
    private mailTransporter: any = null;
    constructor(private httpService: HttpService) {
        // this.testSendCode();
    }
    async testSendCode() {
        this.sendMailCode({ to: '776875292@qq.com', type: '注册账号', code: '000001' })
            .then(() => {
                console.log('发送成功');
            })
            .catch((error) => {
                console.log('发送失败：', error);
            });
    }
    captcha() {
        const currentCaptcha = svgCaptcha.create({
            width: 110,
            height: 40,
            size: 4,
            fontSize: 50,
            background: this.random16Color(),
        });
        return currentCaptcha;
    }
    randomInt(min, max) {
        return Math.floor(Math.random() * (max - min + 1) + min);
    }
    random16Color() {
        const colorWords = [
            ...Array(9)
                .fill(null)
                .map((item, index) => index),
            'a',
            'b',
            'c',
            'd',
            'e',
            'f',
        ];
        return `#${Array(6)
            .fill(null)
            .reduce((pre) => pre + colorWords[this.randomInt(0, 15)], '')}`;
    }
    randomRgb() {
        return `rgb(${(this.randomInt(0, 255), this.randomInt(0, 255), this.randomInt(0, 255))})`;
    }
    randomRgba() {
        return `rgba(${this.randomInt(0, 255)},
    ${this.randomInt(0, 255)},
    ${this.randomInt(0, 255)},
    ${this.randomInt(0.1, 1)})`;
    }
    uploadFile(file) {
        return new Promise((resolve) => {
            const dateString = new Date()
                .toLocaleDateString()
                .split('/')
                .map((item) => item.padStart(2, '0'))
                .join('');
            const originalname = file.originalname;
            const dirPath = path.join(__dirname, `../../../public/${config.uploadDir}`, dateString);
            mkdirp.sync(dirPath);
            const filename = `${Date.now().toString()}-${originalname}`;
            const uploadDir = path.join(dirPath, filename);
            const onlineDir = `${config.assetsPath}/${config.uploadDir}/${dateString}/${filename}`;
            const wr = createWriteStream(uploadDir);
            const imageSize = sizeOf(file.buffer);
            const { width, height } = imageSize;
            wr.write(file.buffer, async () => {
                const { mimetype } = file;
                const supportedMineTypes = ['image/gif', 'image/png', 'image/jpeg', 'image/bmp'];
                const sizeList = config.jimpQualityList;
                if (supportedMineTypes.includes(mimetype)) {
                    try {
                        const lenna = await Jimp.read(uploadDir);
                        sizeList.forEach((scale) => {
                            lenna
                                .resize(width * scale, height * scale) // resize
                                .quality(scale * 100) // set JPEG quality
                                // .greyscale() // set greyscale
                                .write(`${uploadDir}_${scale * 100}${path.extname(uploadDir)}`); // save
                        });
                    } catch (error) {}
                }
                resolve(onlineDir);
            });
        });
    }
    writeFile(buffer: Buffer, name?: string, type?: 'png' | 'jpg' | 'jpeg') {
        return new Promise((resolve, reject) => {
            writeFile(path.join(__dirname, '../../../public', `${name || Date.now()}.${type || '.png'}`), buffer, (err) => {
                if (err) return reject(err);
                resolve(true);
            });
        });
    }
    async fromUrlToBase64(url) {
        const result = await firstValueFrom(
            this.httpService.get(url, { responseType: 'arraybuffer', headers: { referer: 'https://passport.58.com/' } }),
        );
        const resultBase64 = Buffer.from(result.data).toString('base64');
        return resultBase64;
    }
    initMail() {
        this.mailTransporter = nodemailer.createTransport(config.nodeMailConfig.QQ);
    }
    async sendMailCode(options: { to: string; text?: string; html?: string; from?: string; subject?: string; type: string; code: string }) {
        return new Promise(async (resolve, reject) => {
            if (!options.type || !options.code) return reject('请传入type、code');
            if (!this.mailTransporter) this.initMail();
            const mailOptions = {
                ...config.nodeMailConfig.mailOptions,
                html: await getMailCodeTemplate(options.type, options.code),
                ...options,
            };
            this.mailTransporter.sendMail(mailOptions, (err, info) => {
                if (err) return reject(err);
                resolve(info);
            });
        });
    }
    generateOrderId() {
        return `vs${Date.now()}${lodash.random(0, 9999).toString().padStart(4, '0')}`;
    }
    generateMd5(str: string) {
        return md5(str);
    }
}
